import cookie from './cookie'
import localStorage from './localStorage'
import {validator} from './validate'
import constant from '../../bis-meeting/constant/index'
// import router from '@core/router'
import api from '@core/api/'
import {Message, MessageBox} from 'element-ui'
// import store from '@core/store/'

/**
 * 登出
 */
function logout () {
  // 清除cookie
  let url = cookie.getCookie('meeting_ssoredirect_url')
  api.commonService.userLogout()
    .then(data => {
      if (data.errorMessage) {
        Message.error(data.errorMessage)
      } else {
        const { body } = data
        if (body) {
          cookie.deleteCookie('hm_sessionid')
          localStorage.clear()
          // router.push({ name: 'login' })
          window.location.href = url
        }
      }
    })
    .catch(e => {
      console.log(e)
    })
}

function transformationParams (data) {
  let params = ''
  for (let key in data) {
    if (data[key] === 0 || data[key]) {
      if (Object.prototype.toString.call(data[key]) === '[object Array]') {
        params = params + key + '=' + JSON.stringify(data[key]) + '&'
      } else {
        params = params + key + '=' + data[key] + '&'
      }
    }
  }
  return params
}
/**
 * 是否内嵌至PC客户端，若是则不需要登录界面和退出功能
 *
 */
function needLoginPage () {
  return false
}

// 延迟执行，默认300毫秒
let timer = ''
function delayFunc (callback, timeout = 300) {
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    callback && callback()
    timer = ''
  }, timeout)
}
/**
 * 下载文件
 * @param {String} data 二进制数据
 * @param {String} fileName 文件名
 */
function downloadFile (data, fileName) {
  if (window.navigator.msSaveOrOpenBlob) { // ie
    var blob = new Blob([data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    navigator.msSaveBlob(blob, fileName)
  } else {
    let aLink = document.createElement('a')
    let evt = document.createEvent('MouseEvents')
    aLink.href = window.URL.createObjectURL(new Blob([data]))
    aLink.download = fileName || 'download'
    evt.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0)
    aLink.dispatchEvent(evt)
  }
}

/**
 * 下载图片
 * @param {String} url 图片url
 * @param {String} fileName 文件名
 */
function downloadImage (url, fileName) {
  if (window.navigator.msSaveOrOpenBlob) { // ie
    var bstr = atob(url.split(',')[1])
    var n = bstr.length
    var u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    var blob = new Blob([u8arr])
    window.navigator.msSaveOrOpenBlob(blob, fileName)
  } else {
    const aLink = document.createElement('a')
    const evt = document.createEvent('MouseEvents')
    aLink.href = url
    aLink.download = fileName
    evt.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0)
    aLink.dispatchEvent(evt)
  }
}
/**
 * 将时间戳转为完整日期字符串
 * @param {Number} time 时间戳
 */
function timeFormat (time = 0) {
  let date = new Date(+time)
  return `${date.getFullYear()}-${pad0(date.getMonth() + 1)}-${pad0(date.getDate())} ${pad0(date.getHours())}:${pad0(date.getMinutes())}:${pad0(date.getSeconds())}`
}
/**
 * 将时间戳转为完整日期字符串兼容ie
 * @param {Number} time 时间戳
 */
function timeFormatIe (time = 0) {
  if (typeof (time) === 'string') {
    let date = new Date(+time.replace(/-/g, '/'))
    return `${date.getFullYear()}-${pad0(date.getMonth() + 1)}-${pad0(date.getDate())} ${pad0(date.getHours())}:${pad0(date.getMinutes())}:${pad0(date.getSeconds())}`
  } else {
    let date = new Date(+time)
    return `${date.getFullYear()}-${pad0(date.getMonth() + 1)}-${pad0(date.getDate())} ${pad0(date.getHours())}:${pad0(date.getMinutes())}:${pad0(date.getSeconds())}`
  }
}

/**
 * 将时间戳转为完整日期字符串兼容ie
 * @param {Number} time 时间戳
 */
function HourMinutesFormat (time = 0) {
  if (typeof (time) === 'string') {
    let date = new Date(+time.replace(/-/g, '/'))
    return `${date.getFullYear()}-${pad0(date.getMonth() + 1)}-${pad0(date.getDate())} ${pad0(date.getHours())}:${pad0(date.getMinutes())}`
  } else {
    let date = new Date(+time)
    return `${date.getFullYear()}-${pad0(date.getMonth() + 1)}-${pad0(date.getDate())} ${pad0(date.getHours())}:${pad0(date.getMinutes())}`
  }
}
/**
 * new Date()封装兼容ie
 */
function NewDate (str) {
  if (!str) {
    return 0
  }
  let arr = str.split('')
  let d = arr[0].split('-')
  let t = arr[1].split(':')
  let date = new Date()
  date.setUTCFullYear(d[0], d[1] - 1, d[2])
  date.setUTCHours(t[0], t[1], t[2], 0)
  return date
}
/**
 * 将时间戳转为完整日期字符串
 * @param {Number} time 时间戳
 */
function timeFormat2 (time = 0) {
  if (time === null || time === undefined) {
    return '--'
  } else {
    let date = new Date(time)
    return `${date.getFullYear()}-${pad0(date.getMonth() + 1)}-${pad0(date.getDate())} ${pad0(date.getHours())}:${pad0(date.getMinutes())}`
  }
}

function timeFormat3 (time = 0) { // 0.00转23.59
  if (time === null || time === undefined) {
    return '--'
  } else {
    let date = new Date(time)
    return `${date.getFullYear()}-${pad0(date.getMonth() + 1)}-${pad0(date.getDate())} ` + (date.getHours() === 0 ? (date.getMinutes() === 0 ? '23:59' : `00:${pad0(date.getMinutes())}`) : `${pad0(date.getHours())}:${pad0(date.getMinutes())}`)
  }
}

function timeFormatIe2 (time = 0) { // 兼容ie
  if (time === null || time === undefined) {
    return '--'
  } else {
    let date = new Date(time)
    return `${date.getFullYear()}/${pad0(date.getMonth() + 1)}/${pad0(date.getDate())}`
  }
}
/**
 * 将时间戳转为时分
 * @param {Number} time 时间戳
 */
function HMFormat (time = 0) {
  if (time === null || time === undefined) {
    return '--'
  } else {
    let date = new Date(time)
    return `${pad0(date.getHours())}:${pad0(date.getMinutes())}`
  }
}
/**
 * 将时间戳转为日期字符串
 * @param {Number} time 时间戳
 */
function dateFormat (time = 0, space) {
  let date = new Date(+time)
  if (!space) {
    return `${date.getFullYear()}年${pad0(date.getMonth() + 1)}月${pad0(date.getDate())}日`
  } else {
    return `${date.getFullYear()}` + space + `${pad0(date.getMonth() + 1)}` + space + `${pad0(date.getDate())}`
  }
}

/**
 * 根据日期得到周几
 * @param time
 */
function weekDayFormat (time = 0) {
  var weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  let date = new Date(+time)
  return weekDay[date.getDay()]
}
/**
 * 在字符串前补零
 * @param {String} str 原字符串
 * @param {Number} count 补零个数
 */
function pad0 (str = '', count = 2) {
  let padStr = ''
  str = str + ''
  let add = count - str.length
  if (add > 0) {
    for (let i = 0; i < add; ++i) {
      padStr += '0'
    }
  }
  return padStr + str
}

/**
 * 对字符串内容进行校验
 * @param {String}} type  校验类型
 * @param {String} val 要校验的字符串
 */
function validate (type, val = '') {
  let v = validator[type]

  return v && v.test(val)
}

/**
 * 对文件名格式化
 * @param {String}} filename 文件名转换
 */
function filenameFormat (filename = '') {
  let name = filename.toString().split('.')
  if (name.length > 1) {
    let firstname = name[0].length > 15 ? name[0].slice(0, 15) + '... ' : name[0].slice(0)
    filename = `${firstname}.${name[1]}`
  }
  return filename
}

/**
 * 对路径格式化
 * @param {String}} pathname 路径格式化
 */
function pathFormat (pathList = []) {
  let newPathList = []
  return newPathList
}

/*
* 是否显示分页
* 总数小于10条数据不显示分页
* @param {Number} val 总条数
*/
function isOrNotPage2 (val = 0) {
  return val > 10 ? 'total, prev, pager, next' : 'total'
}
function isOrNotPage (val = 0) {
  return val > 10 ? 'total, prev, pager, next,sizes,jumper' : 'total'
}
/**
 * 封装删除最后一条时页码改变
 * @param min: 页码的最小值
 * @param curPage: 当前页码
 * @param listlength 当前页总条数
 */
function changeCurpageSize (curPage, listlength, min = 1) {
  let goPageSize = curPage
  if (listlength === 1) { // 当是最后一条
    if (curPage > min) { // 当前页码大于最小页码
      goPageSize -= 1
    }
  }
  return goPageSize
}
/*
* 格式化提案时间
*/
function formatProposalTime (val) {
  if (typeof val === 'string') {
    return val.replace(/,/g, '')
  } else {
    return val
  }
}

/*
 * 过滤出有权限的路由
 * @param {String} menuIdArr 权限menuId数组
 * @param {String} routerTree 路由树
 */
function validRouters (routerTree, menuIdArr) {
  const result = []
  let temp = []
  for (let i = 0; i < routerTree.length; i++) {
    if (routerTree[i].meta.type !== 'menu') { // 只过滤type!== 'menu'或 type==='menu && menuId存在menuIdArr中
      result.push(routerTree[i])
    } else if (menuIdArr.indexOf(routerTree[i].meta.menuId) >= 0) { // 当路由树中的id和menuIdArr中存在的话
      const obj = routerTree[i]
      if (obj.children && obj.children.length > 0) {
        temp = validRouters(obj.children, menuIdArr)
      } else {
        temp = []
      }
      if (temp.length > 0) {
        obj.children = temp
      } else {
        obj.children = []
      }
      result.push(obj)
    }
  }
  return result
}

/*
 * 格式化空
 */
function filterNull (val) {
  if (!val || val === '0') {
    return '--'
  } else {
    return val
  }
}

/*
 * 格式化状态
 */
function filterStatus (arr, val) {
  arr = arr || []
  let hasStatus = arr.find(item => item.value === val)
  if (hasStatus) {
    return hasStatus.label
  } else {
    return '--'
  }
}
// 会议状态
function getMeetApprovalStatus (row) { // 判断会议状态
  if (row.meetingStatus === 1 || row.meetingStatus === 2 || row.meetingStatus === 3) {
    return filterStatus(constant.meetingStatus, row.meetingStatus)
  } else {
    if (row.apMeetFlag === 2) {
      return '领导审核不通过'
    } else {
      if (row.apRoomFlag === 2) {
        return '会议室审核不通过'
      }
      if (row.apMeetFlag === 0) {
        return '待领导审核'
      }
      if (row.apRoomFlag === 0) {
        return '待审核会议室'
      }
      return '未开始'
    }
  }
}

// 获取其他信息
function getOtherMeetingInfo (data) {
  let temp = {
    videoFlag: data['videoFlag'],
    cardFlag: data['cardFlag'],
    cardContent: data['cardContent'],
    drinksFlag: data['drinksFlag'],
    projectorFlag: data['projectorFlag'],
    enSignup: data['enSignup'],
    enSignupEnd: data['enSignupEnd'],
    remindTime: data['remindTime'],
    signupFlag: data['signupFlag'],
    signTime: data['signTime'],
    secretary: data['secretary'],
    serverFlag: data['serverFlag']
  }
  return temp
}
/**
 * @param monthCount 当前时间后的月份数
 */
function timeControlForMonths (monthCount) {
  var d = new Date()
  let endYear = d.getFullYear()
  let endMonth = d.getMonth() + 1
  let endDay = d.getDate()
  // let endFullMonthDays = new Date(endYear, endMonth, 0).getDate()
  let startYear = endYear
  let startMonth = endMonth - monthCount
  let startDay = endDay
  let startFullMonthDays
  if (startMonth <= 0) { // 查询时间跨越两年
    startYear--
    startMonth = 12 - (-startMonth)
  }
  startFullMonthDays = new Date(startYear, startMonth, 0).getDate()
  console.log(startMonth + '月有' + startFullMonthDays + '天')
  if (endDay > startFullMonthDays) startDay = startFullMonthDays // 开始月份没有那么多天，按开始月份最后一天算
  endMonth = endMonth < 10 ? '0' + endMonth : endMonth
  endDay = endDay < 10 ? '0' + endDay : endDay
  startMonth = startMonth < 10 ? '0' + startMonth : startMonth
  startDay = startDay < 10 ? '0' + startDay : startDay
  console.log('查询 ' + startYear + '-' + startMonth + '-' + startDay + ' 到 ' + endYear + '-' + endMonth + '-' + endDay)
  return new Date(startYear + '-' + startMonth + '-' + startDay + ' 00:00:00')
}

/**
 * 封装提示消息
 */
function hasMessageDialog (message, type, callback) {
  if (document.querySelector('.el-message')) {
    return false
  } else {
    Message({
      type: type || 'error',
      message: `${message}`,
      onClose: function () {
        if (callback) { callback() }
      }
    })
  }
}

/*
* 格式化图片及附件路径
*/
function formatImgUrl (value) {
  const pro = window.location.protocol
  const url = window.location.host
  let albumurlTrim = value ? value.trim() : ''
  let albumurlVal = /(^(http|https|HTTP|HTTPS):\/\/\.*)/.test(albumurlTrim) ? albumurlTrim : (albumurlTrim ? (`${pro}//${url}/userplatforms/rest/file/download?url=` + albumurlTrim) : '')
  // let albumurl = albumurlVal || (domain + '/open/imagetext/images/common_def_people_nor.png')
  let albumurl = albumurlVal
  return albumurl
}

// 统一二次确认框
function confirmTip (title, content, callback, type, sureTxt, cancelText) {
  MessageBox.confirm(content, title, {
    confirmButtonText: sureTxt || '确定',
    cancelButtonText: cancelText || '取消',
    type: type || 'warning',
    customClass: 'auto-confirm',
    dangerouslyUseHTMLString: true,
    center: true
  }).then(() => {
    console.log('成功。。。')
    console.log(callback)
    callback()
    // if (callback) callback()
  }).catch(() => {
    hasMessageDialog('已取消操作', 'info')
  })
}
const utils = {
  logout,
  needLoginPage,
  ...cookie,
  validate,
  transformationParams,
  downloadFile,
  downloadImage,
  timeFormat,
  timeFormat2,
  HMFormat,
  dateFormat,
  isOrNotPage2,
  changeCurpageSize,
  isOrNotPage,
  filenameFormat,
  pathFormat,
  weekDayFormat,
  formatProposalTime,
  validRouters,
  filterNull,
  filterStatus,
  getMeetApprovalStatus,
  timeFormatIe,
  HourMinutesFormat,
  NewDate,
  delayFunc,
  timeControlForMonths,
  hasMessageDialog,
  formatImgUrl,
  confirmTip,
  getOtherMeetingInfo,
  timeFormat3,
  timeFormatIe2
}

for (let key in localStorage) {
  utils[key + 'Session'] = localStorage[key]
}

export default utils
